<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>22软件工程班课表</title>
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/4.5.2/css/bootstrap.min.css">
    <style>
        .modal-dialog-centered {
            display: flex !important;
            align-items: center;
            justify-content: center;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            overflow: auto;
            min-height: calc(100% - 1rem);
        }
        /* 分页样式 */
        .pagination-container {
            display: flex;
            justify-content: flex-end;
            margin-top: 20px;
            align-items: center; /* 添加垂直居中对齐 */
        }
        .page-info {
            margin: 0 15px;
            /* 移除line-height，使用align-items控制垂直对齐 */
        }
        /* 调整分页按钮的行高 */
        .pagination {
            margin: 0;
            align-items: center; /* 确保分页按钮也垂直居中 */
        }
        .page-link {
            line-height: 1.2; /* 调整链接行高 */
            padding: 0.5rem 0.75rem; /* 调整内边距 */
        }
        /* 表格底部留白 */
        .table-container {
            margin-bottom: 30px;
        }
        /* 下拉框样式 - 设置固定高度和滚动条 */
        #course-select {
            max-height: 200px;
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <div class="header text-center mb-4">
        <h2>22软件工程班课表</h2>

        <!-- 修改后的课程选择下拉框 -->
        <div class="form-group">
            <label for="course-select">选择课程</label>
            <select class="form-control" id="course-select" size="1">
                <option value="">请选择课程</option>
            </select>
        </div>

        <!-- 添加和编辑按钮 -->
        <div class="d-flex justify-content-center">
            <button class="btn btn-success mr-2" id="add-btn">添加课程</button>
            <button class="btn btn-primary" id="edit-btn" disabled>编辑课程</button>
        </div>
    </div>

    <div class="table-container">
        <table id="schedule-table" class="table table-striped">
            <thead>
            <tr>
                <th>课程编号</th>
                <th>课程名称</th>
                <th>学分</th>
                <th>授课教师编号</th>
            </tr>
            </thead>
            <tbody>
            </tbody>
        </table>
    </div>

    <!-- 分页控件 -->
    <div class="pagination-container">
        <nav aria-label="Page navigation">
            <ul class="pagination" id="pagination">
                <li class="page-item disabled" id="prev-page">
                    <a class="page-link" href="#" aria-label="Previous">
                        <span aria-hidden="true">&laquo;</span>
                    </a>
                </li>
                <!-- 页码将通过JS动态生成 -->
                <li class="page-item disabled" id="next-page">
                    <a class="page-link" href="#" aria-label="Next">
                        <span aria-hidden="true">&raquo;</span>
                    </a>
                </li>
            </ul>
        </nav>
        <div class="page-info" id="page-info">第1页/共1页</div>
    </div>

<!-- 模态框 -->
<div class="modal fade" tabindex="-1" role="dialog" id="editModal">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">课程信息</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="关闭">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                <form id="editForm">
                    <div class="form-group">
                        <label for="courseNo">课程编号</label>
                        <input type="text" class="form-control" id="courseNo" disabled>
                    </div>
                    <div class="form-group">
                        <label for="courseName">课程名称</label>
                        <input type="text" class="form-control" id="courseName">
                    </div>
                    <div class="form-group">
                        <label for="credit">学分</label>
                        <input type="text" class="form-control" id="credit">
                    </div>
                    <div class="form-group">
                        <label for="teacherNo">授课教师编号</label>
                        <input type="text" class="form-control" id="teacherNo">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="save-changes">保存更改</button>
            </div>
        </div>
    </div>
</div>

<!-- 脚本依赖（Bootstrap 4 + Popper.js 1.x） -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

<script>
    const editBtn = document.getElementById('edit-btn');
    const addBtn = document.getElementById('add-btn');
    const saveChangesBtn = document.getElementById('save-changes');
    const table = document.getElementById('schedule-table');
    const courseSelect = document.getElementById('course-select');
    const pagination = document.getElementById('pagination');
    const prevPage = document.getElementById('prev-page');
    const nextPage = document.getElementById('next-page');
    const pageInfo = document.getElementById('page-info');

    let currentCourseNo = null;
    let currentPage = 1;
    let totalPages = 1;
    const pageSize = 10; // 每页显示10条内容

    // 加载所有课程数据（用于下拉框）
    function loadAllCourses() {
        fetch('/system/sysRole/course')
            .then(res => res.json())
            .then(courses => {
                courseSelect.innerHTML = '<option value="">请选择课程</option>';

                courses.forEach(course => {
                    const option = document.createElement('option');
                    option.value = course.courseNo;
                    option.textContent = `${course.courseNo} - ${course.courseName}`;
                    courseSelect.appendChild(option);
                });
            })
            .catch(error => console.error('加载课程数据失败:', error));
    }

    // 加载分页课程数据（用于表格）
    function loadCourses(page = 1) {
        currentPage = page;
        const url = `/system/sysRole/pageRole?current=${page}&size=${pageSize}`;

        fetch(url)
            .then(res => res.json())
            .then(data => {
                const courses = data.records || [];
                totalPages = data.pages || 1;

                // 更新表格数据
                const tableBody = table.querySelector('tbody');
                tableBody.innerHTML = '';

                courses.forEach(course => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${course.courseNo}</td>
                        <td>${course.courseName}</td>
                        <td>${course.credit}</td>
                        <td>${course.teacherNo}</td>
                    `;
                    tableBody.appendChild(row);
                });

                // 更新分页控件
                updatePagination();
                updatePageInfo();
            })
            .catch(error => console.error('加载课程数据失败:', error));
    }

    // 更新分页按钮
    function updatePagination() {
        while (pagination.children.length > 2) {
            pagination.removeChild(pagination.children[1]);
        }

        const startPage = Math.max(1, currentPage - 2);
        const endPage = Math.min(totalPages, currentPage + 2);

        for (let i = startPage; i <= endPage; i++) {
            const li = document.createElement('li');
            li.className = `page-item ${i === currentPage ? 'active' : ''}`;
            li.innerHTML = `<a class="page-link" href="#" data-page="${i}">${i}</a>`;
            li.addEventListener('click', (e) => {
                e.preventDefault();
                loadCourses(i);
            });
            pagination.insertBefore(li, nextPage);
        }

        prevPage.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
        nextPage.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
    }

    // 更新页码信息
    function updatePageInfo() {
        pageInfo.textContent = `第${currentPage}页/共${totalPages}页`;
    }

    // 初始化页面
    window.onload = () => {
        loadAllCourses(); // 加载所有课程到下拉框
        loadCourses();    // 加载第一页课程到表格

        prevPage.querySelector('a').addEventListener('click', (e) => {
            e.preventDefault();
            if (currentPage > 1) {
                loadCourses(currentPage - 1);
            }
        });

        nextPage.querySelector('a').addEventListener('click', (e) => {
            e.preventDefault();
            if (currentPage < totalPages) {
                loadCourses(currentPage + 1);
            }
        });

        courseSelect.onchange = () => {
            currentCourseNo = courseSelect.value || null;
            editBtn.disabled = !currentCourseNo;
        };
    };

    // 编辑按钮
    editBtn.onclick = () => {
        if (!currentCourseNo) {
            alert("请选择一门课程进行编辑！");
            return;
        }

        fetch(`/system/sysRole/course/${currentCourseNo}`)
            .then(res => res.json())
            .then(course => {
                if (!course) {
                    alert("未找到该课程！");
                    return;
                }
                document.getElementById('courseNo').value = course.courseNo;
                document.getElementById('courseName').value = course.courseName;
                document.getElementById('credit').value = course.credit;
                document.getElementById('teacherNo').value = course.teacherNo;

                $('#editModal').modal('show');
            })
            .catch(error => console.error('加载编辑数据失败:', error));
    };

    // 添加按钮
    addBtn.onclick = () => {
        document.getElementById('courseNo').value = '';
        document.getElementById('courseName').value = '';
        document.getElementById('credit').value = '';
        document.getElementById('teacherNo').value = '';
        currentCourseNo = null;

        $('#editModal').modal('show');
    };

    // 保存更改按钮
    saveChangesBtn.onclick = () => {
        const updatedCourse = {
            courseNo: currentCourseNo ? parseInt(currentCourseNo) : null,
            courseName: document.getElementById('courseName').value,
            credit: document.getElementById('credit').value,
            teacherNo: document.getElementById('teacherNo').value
        };

        const url = `/system/sysRole/course`;
        const method = 'POST';
        const bodyData = JSON.stringify([updatedCourse]);

        fetch(url, {
            method: method,
            headers: { 'Content-Type': 'application/json' },
            body: bodyData
        })
            .then(res => res.json())
            .then(result => {
                alert(currentCourseNo ? '更新成功！' : '添加成功！');
                $('#editModal').modal('hide');
                loadAllCourses(); // 重新加载下拉框
                loadCourses(currentPage); // 重新加载当前页表格数据
            })
            .catch(error => {
                console.error('保存失败:', error);
                alert('保存课程失败！');
            });
    };
</script>
</body>
</html>